'use server';

import { getSession } from '@/lib/auth';
import { db } from '@/lib/db';
import { product, shop } from '@/lib/db/schema/common';
import { extractWords, gorse } from '@/lib/gorse';
import { result, withZod } from '@/lib/utils';
import { and, eq, sql } from 'drizzle-orm';
import { revalidatePath } from 'next/cache';
import { z } from 'zod';
import { BizError, ErrorCode } from '../error';
import { productFormSchema } from './schema/product';

const checkProductExist = async (userId: string, productId: number) => {
  const res = await db
    .select({
      exists: sql<number>`1`,
    })
    .from(product)
    .innerJoin(shop, eq(shop.id, product.shopId))
    .where(and(eq(shop.userId, userId), eq(product.id, productId)));
  return !!res[0]?.exists;
};

export const createProduct = withZod(
  productFormSchema.extend({
    imageKeys: z.array(z.string()),
  }),
  async ({ name, price, description, imageKeys }) => {
    try {
      const session = await getSession();
      if (!session?.user)
        throw new BizError(ErrorCode.Unauthorized, '用户未登录');
      const shopItem = await db.query.shop.findFirst({
        columns: { id: true },
        where: (shop, { eq }) => eq(shop.userId, session.user.id),
      });
      if (!shopItem) throw new BizError(ErrorCode.NotFound, '店铺不存在');
      await db.insert(product).values({
        name,
        price,
        description,
        imageKeys,
        shopId: shopItem.id,
      });
      gorse.mergeItemLabels({
        id: String(shopItem.id),
        labels: extractWords(name.concat(' ').concat(description ?? ''), 3),
      });
      revalidatePath('/shop/product');
      return result();
    } catch (error) {
      return result(error, '创建外卖失败,请重试');
    }
  },
);

export const deleteProduct = withZod(z.number(), async (id) => {
  try {
    const session = await getSession();
    if (!session?.user)
      throw new BizError(ErrorCode.Unauthorized, '用户未登录');
    if (!(await checkProductExist(session.user.id, id)))
      throw new BizError(ErrorCode.NotFound, '外卖不存在');
    await db.delete(product).where(eq(product.id, id));
    revalidatePath('/shop/product');
    return result();
  } catch (error) {
    return result(error, '删除外卖失败,请重试');
  }
});

export const updateProduct = withZod(
  productFormSchema.extend({
    id: z.number(),
    imageKeys: z.array(z.string()),
  }),
  async ({ id, name, price, description, imageKeys }) => {
    try {
      const session = await getSession();
      if (!session?.user)
        throw new BizError(ErrorCode.Unauthorized, '用户未登录');
      if (!(await checkProductExist(session.user.id, id)))
        throw new BizError(ErrorCode.NotFound, '外卖不存在');
      const res = await db
        .update(product)
        .set({ name, price, description, imageKeys })
        .where(eq(product.id, id))
        .returning({ shopId: product.shopId });
      gorse.mergeItemLabels({
        id: String(res[0].shopId),
        labels: extractWords(name.concat(' ').concat(description ?? ''), 3),
      });
      revalidatePath('/shop/product');
      return result();
    } catch (error) {
      return result(error, '更新外卖失败,请重试');
    }
  },
);
